import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {connect} from 'react-redux';
import {View, Text} from '@tarojs/components';
import {AtIcon} from 'taro-ui';
import {GetRequest} from "../../utils/tools";
import {http} from "../../utils/http";
import {TARO_ENV, RESOURCE_URL} from "../../constants/api";
import "./index.scss";

export default class WiFiCode extends Component {
	constructor(props) {
		super(props);
		this.state = {
			imgSrc: ""
		};
	}

	async componentDidShow() {}

	// down
	handleDown = async () => {
		const setting = await Taro.getSetting()
		if (!setting.authSetting['scope.writePhotosAlbum']) {
			const r = await Taro.authorize({
				scope: 'scope.writePhotosAlbum',
			}).catch(() => {
				Taro.showModal({
					title: '提示',
					content: '我们需要权限帮您保存到相册，请打开保存到相册',
					cancelText: '不需要',
					confirmText: '好的',
					success: (ret) => {
						if (ret.confirm) {
							Taro.openSetting()
						}
					}
				})
			})
		}

		const { codeUrl } = this.props;
		console.log("codeUrl +++++++++++ : ", codeUrl);
		Taro.getImageInfo({
			src: codeUrl,
		}).then((res) => {
			console.log("res ======== : ", res);
			Taro.hideLoading()
			this.setState({imgSrc: res.path}, () => {
				console.log("imgSrc ------- : ", this.state.imgSrc)
				this.savePhoto(res.path);
			})
		}).catch(err => {
			Taro.hideLoading()
			//console.log(err)
			Taro.showToast({title: '图片不存在', icon: 'none'})
		})
	}
	// save img
	savePhoto(imgSrc) {
		Taro.saveImageToPhotosAlbum({
			filePath: imgSrc,
		}).then(() => {
			Taro.showToast({
				title: '保存成功，请进入相册查看',
				icon: 'none'
			})
		})
	}
	// preview
	handlePreview = () => {
		const { codeUrl } = this.props;
		wx.previewImage({
			urls: [codeUrl]
		})
	}

	render() {
		return (
			<View className="code-layer">
				<View className="code-container">
					<View className="code-box">
						<Image src={this.props.codeUrl} className="code-img" onClick={this.handlePreview} />
						<View className="down-code" onClick={this.handleDown}>
							<AtIcon
								value="download-cloud"
								size="18"
								color="#FEA000"
								className="code-icon"
							/>
							<Text className="down-text">点击下载Wi-Fi码</Text>
						</View>
					</View>
					<View className="code-line"></View>
					<View className="code-close">
						<AtIcon
							value="close-circle"
							size="28"
							color="#fff"
							className="close-icon"
							onClick={this.props.handleClose}
						/>
					</View>
				</View>
			</View>
		)
	}
}
